package au.com.somethingwritten.model;

import java.util.ArrayList;

public class ShoppingCart {
	ArrayList<CartItem> items;
	
	public ShoppingCart(){
		this.items = new ArrayList<CartItem>();
	}
	
	public void addItem(Book item, Integer quantity){
		boolean notFound = true;
		int i = 0;
		//try and find a matching book in the cart
		while(i < items.size() && notFound){
			//if a matching book is found, update the quantity
			if(items.get(i).getItem().getId() == item.getId()){
				notFound = false;
				items.get(i).setQuantity(items.get(i).getQuantity() + quantity);
			}
			i++;
		}
		//if book is not already in cart, add it to the cart
		if(notFound)
			this.items.add(new CartItem(item, quantity));
	}
	
	public void updateQuantity(Book item, Integer quantity){
		if(quantity < 1){
			removeItem(item);
		}else{
			updateItem(item, quantity);
		}
	}
	
	public void updateItem(Book item, Integer quantity){
		boolean notFound = true;
		int i = 0;
		//try and find a matching book in the cart
		while(i < items.size() && notFound){
			//if a matching book is found, update the quantity
			if(items.get(i).getItem().getId() == item.getId()){
				notFound = false;
				items.get(i).setQuantity(quantity);
			}
			i++;
		}
	}
	
	public void addItem(CartItem item){
		this.items.add(item);
	}
	
	public ArrayList<CartItem> getAllItems(){
		return this.items;
	}
	
	public void removeItem(CartItem item){
		this.items.remove(item);
	}
	
	public void removeItem(Book item){
		boolean notFound = true;
		int i = 0;
		Integer ix = null;
		while(notFound && i < items.size()){
			if(items.get(i).getItem().getId() == item.getId()){
				ix = i;
				notFound = false;
			}
			i++;
		}
		
		if(ix != null){
			this.items.remove((int)ix);
		}
	}
	
	public Integer getTotalItems(){
		int total = 0;
		//count the quantity of each item
		for(int i = 0;i < size(); i++)
			total += items.get(i).getQuantity();

		return total;
	}
	
	public Integer size(){
		return this.items.size();
	}
	
	public CartItem get(int index){
		return this.items.get(index);
	}
	
	public Double getCost(){
		Double cost = 0.0;
		//add up costs, multiplied by quantity.
		for(int i = 0; i < items.size(); i++){
			cost += (items.get(i).getItem().getPrice() * items.get(i).getQuantity());
		}
		return cost;
	}
}
